package com.simba.server.commands.impl.web;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.simba.common.command.ICommand;
import com.simba.common.utils.StringUtil;
import com.simba.server.base.CommonUtil;
import com.simba.server.base.TimeUtil;
import com.simba.server.components.MachineParams;
import com.simba.server.components.SortCommonDefines;
import com.simba.server.components.SorterParams;
import com.simba.server.components.data.*;
import org.apache.log4j.Logger;

import com.simba.common.log.LogUtil;
import com.simba.server.ServerParam;
import com.simba.server.webservice.WebServiceManager;

/**
 * 格口状态回传
 */
public class WebSlotStatusCmd implements ICommand
{
	public static final String NAME = "WebSlotStatusCmd";
	private static final Logger logger = Logger.getLogger(WebSlotStatusCmd.class);
	private SlotInfo slotInfo;

	public WebSlotStatusCmd(SlotInfo slotInfo)
	{
		this.slotInfo = slotInfo;
	}

	@Override
	public String getName()
	{
		return WebSlotStatusCmd.NAME;
	}

	@Override
	public Boolean run(Object params)
	{
		boolean ret = false;
		String remoteMethod = "AutoSort/LockChute";

		Map<String, Object> rp = new HashMap<>();
		//自动生成
		rp.put("Guid", TimeUtil.getTimeDateString("yyMMddHHmmss", new Date())+CommonUtil.getRandom(1000000000L));
		//格口号
		rp.put("ChuteCode", CommonUtil.doNullData(slotInfo.getSlotId(), "0"));
		//分拣机代码
		rp.put("MachineCode", MachineParams.getInstance().getDeviceId());
		//是否锁格（1 锁格，0 解锁）
		rp.put("Status",CommonUtil.doNullData(String.valueOf(slotInfo.getLockStatus()), "0"));
		//请求时间
		rp.put("RequestTime", TimeUtil.getTimeDateString("yyyy-MM-dd HH:mm:ss", new Date()));
		Gson gson = CommonUtil.getGson();
		String content = gson.toJson(rp);
		try
		{
			if (SorterParams.getInstance().isDebugMode()){
				LogUtil.LogError(logger, "upload slot state error: debug mode doesn't upload data!");
				return false;
			}

			ResultInfo response = WebServiceManager.getInstance().doHttpServiceByPost(
					ServerParam.REMOTE_WEBSERVICE_ADDRESS, remoteMethod, content);
			if (response != null && response.getCode() >= 200 && response.getCode() < 202)
			{
				ret = this.handleResponse(response);
			}
		}
		catch (Exception e)
		{
			LogUtil.LogError(WebSlotStatusCmd.logger, "upload slot state error: " + e);

		}
		return ret;
	}

	private boolean handleResponse(ResultInfo response)
	{
		boolean ret = false;
		try
		{
			ResultBase result = CommonUtil.getGson().fromJson(response.getData(), ResultBase.class);
			switch (result.getCode())
			{
				case 200:
					ret = true;
					break;
				default:
					LogUtil.LogError(logger, "request slot status failed : [ " + response.getCode()+" ], msg: "+response.getData());
					break;
			}
		}
		catch (Exception e)
		{
			LogUtil.LogError(logger, "parse slot status result failed : " + e);
		}
		return ret;
	}
}
